package com.hpxx.ylzswl.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.adapter.ChooseAdapter;
import com.hpxx.ylzswl.base.BaseActivity;
import com.hpxx.ylzswl.bean.ChooseBean;
import com.hpxx.ylzswl.event.MoneyEvent;
import com.hpxx.ylzswl.https.HttpAddress;
import com.hpxx.ylzswl.https.RequestParams;
import com.hpxx.ylzswl.info.ManageInfo;
import com.hpxx.ylzswl.views.NoScrollingListView;
import com.universal.frame.generalutils.DecimalUtil;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;
import com.universal.frame.pulltorefresh.PullToRefreshBase;
import com.universal.frame.pulltorefresh.PullToRefreshScrollView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Request;

/**
 * Created by Administrator on 2017/11/14.
 */

public class ChooseActivity  extends BaseActivity implements ResultCallBack, View.OnClickListener,PullToRefreshBase.OnRefreshListener{
    private PullToRefreshScrollView pull_refresh_scrollview;
    private NoScrollingListView nsl_list;
    private ChooseAdapter chooseAdapter;
    private List<ChooseBean> list = new ArrayList<ChooseBean>();
    private EditText et_sea_con;
    private LinearLayout ll_search;
    private LinearLayout ll_search_isgone;
    private String total="0";
    private  String price;
    private EditText ed_money;
    private TextView tv_sumbit;
    private int pageIndex = 0;
    private boolean toRefresh = true;
    private String content;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
    }
    //检查项目接口
    private void itemPost(String itemName,int pageIndex){
        OKHttpUtils.postAsync(this
                , HttpAddress.ORDER_ITEMS_URL
                , new RequestParams(this).getOrderItemParams(itemName,pageIndex), this
                ,true,1);
    }
    @Override
    public void initView() {
        back();
        setTitle("选择项目");
        tv_sumbit = (TextView) findViewById(R.id.tv_sumbit);
        et_sea_con = (EditText) findViewById(R.id.et_sea_con);
        et_sea_con.setFilters(new InputFilter[]{emojiFilter});
        ll_search = (LinearLayout) findViewById(R.id.ll_search);
        ll_search_isgone = (LinearLayout) findViewById(R.id.ll_search_isgone);
        pull_refresh_scrollview = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        nsl_list = (NoScrollingListView) findViewById(R.id.nsl_list);
        ed_money = (EditText) findViewById(R.id.ed_money);
        ed_money.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        ed_money.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        ed_money.setText(s);
                        ed_money.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    ed_money.setText(s);
                    ed_money.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        ed_money.setText(s.subSequence(0, 1));
                        ed_money.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        ll_search.setOnClickListener(this);
        tv_sumbit.setOnClickListener(this);
        itemPost("",pageIndex);
        initOrderList();
        initScrollView();
    }
    public void initScrollView() {
        this.pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setPullLabel(
                        getResources().getString(
                                R.string.pull_to_refresh_pull_label_up));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setRefreshingLabel(
                        getResources().getString(
                                R.string.pull_to_refresh_refreshing_label));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setReleaseLabel(
                        getResources().getString(
                                R.string.pull_to_refresh_release_label));

//        pull_refresh_scrollview.setMode(PullToRefreshBase.Mode.BOTH);//both  可以上拉、可以下拉
        pull_refresh_scrollview.setOnRefreshListener(this);
    }
    private void initOrderList(){
        chooseAdapter = new ChooseAdapter(this,list);
        nsl_list.setAdapter(chooseAdapter);
        nsl_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num = ed_money.getText().toString().trim();
                price = list.get(position).itemPrice;
                if ("0".equals(num) || TextUtils.isEmpty(num)||"0.0".equals(num)||"0.00".equals(num)||"0.".equals(num) ){
                    total = "0";
                    total = DecimalUtil.strAdd(price,total,2);
                }else {
                    total = num;
                    total = DecimalUtil.strAdd(price,total,2);
                }
                ed_money.setText(total+"");
            }
        });
    }

    @Override
    public void onSuccess(String response, int flag) {
        int status = JsonUtil.getInt(response, "status", 0);
        try {
            switch (flag) {
                case 1:
                    itemDetail(response);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(this, e);
        }
    }

    private void itemDetail(String response) {
        pull_refresh_scrollview.onRefreshComplete();
        int status = JsonUtil.getInt(response, "status", 0);
        String msg = JsonUtil.getString(response,"msg","");
        if (status == 1){
            String data = JsonUtil.getString(response, "data", "");
            ManageInfo info = JSON.parseObject(data, ManageInfo.class);
            if (info.testItemList != null) {
                if (info.testItemList.size()>0){
                    if (pageIndex ==0) {
                        list.clear();
                        list.addAll(info.testItemList);
                    } else {
                        list.addAll(info.testItemList);
                    }
                    if (info.testItemList.size() < 20) {
                        toRefresh = false;
                    } else {
                        toRefresh = true;
                    }
                    ll_search_isgone.setVisibility(View.GONE);
                    pull_refresh_scrollview.setVisibility(View.VISIBLE);
                }
                else {
                    ll_search_isgone.setVisibility(View.VISIBLE);
                    pull_refresh_scrollview.setVisibility(View.GONE);
                }

                chooseAdapter.notifyDataSetChanged();
            }
        }else {
            ToastUtil.showToast(getApplicationContext(),msg);
        }
    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {
        pull_refresh_scrollview.onRefreshComplete();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_search:
                content = et_sea_con.getText().toString().trim();
                Log.e("lzx", "onClick: "+content+"content" );
                pageIndex =0;
                itemPost(content,pageIndex);
                break;
            case R.id.tv_sumbit:
                String money = ed_money.getText().toString().trim();
                if ( TextUtils.isEmpty(money)) {
                    ToastUtil.showToast(getApplicationContext(), "请添加项目");
                    return;
                }
                if ("0".equals(money) || TextUtils.isEmpty(money)||"0.0".equals(money)||"0.00".equals(money)||"0.".equals(money)  ) {
                    ToastUtil.showToast(getApplicationContext(), "请输入大于0的数字");
                    return;
                }
                EventBus.getDefault().post(new MoneyEvent(money));
                finish();
                break;
            default:
                break;
        }
    }
    InputFilter emojiFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {

                return "";
            }
            return null;
        }
    };


    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        if (toRefresh) {
            content = et_sea_con.getText().toString().trim();
            pageIndex++;
            itemPost(content,pageIndex);
        } else {
            ToastUtil.showToast(this, "没有更多数据");
            pull_refresh_scrollview.onRefreshComplete();
        }
    }
}
